#!/bin/sh

PID_PATH=/root/gateway.pid
EXE_PATH=/usr/bin/gateway
OTA_PATH=/root/gateway.update
BAK_PATH=/root/gateway.bak

# 启动程序进程
start() {
    # 如果OTA文件存在
    if [ -f $OTA_PATH ]; then
        # 对当前文件进行备份
        mv $EXE_PATH $BAK_PATH
        # 将OTA文件移动为当前执行文件
        mv $OTA_PATH $EXE_PATH
        # 给新的程序文件添加执行权限
        chmod +x $EXE_PATH
    fi

	start-stop-daemon -S -q -p $PID_PATH \
		--exec $EXE_PATH -- daemon
	[ $? = 0 ] && echo "OK" || echo "FAIL"
}

# 停止程序进程
stop() {
	start-stop-daemon -K -q -p $PID_PATH
	[ $? = 0 ] && echo "OK" || echo "FAIL"
}

# 重启程序进程
restart() {
	stop
	start
}

case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart|reload)
  	restart
	;;
  *)
	echo "Usage: $0 {start|stop|restart}"
	exit 1
esac

exit $?
